package controllers

import (
	"beego/comm/db"
	"beego/comm/entity"
	"encoding/json"
	"fmt"
	"strconv"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type QueryPwdController struct {
	beego.Controller
}

func (c *QueryPwdController) QueryPwd() {
	defer func() {
		err := recover()
		if nil != err {
			c.Data["json"] = map[string]interface{}{
				"pwd":   nil,
				"count": 0,
				"error": err,
			}
			c.ServeJSON()
		}
	}()
	var pm entity.PwdMap
	json.Unmarshal(c.Ctx.Input.RequestBody, &pm)
	user_name := pm.UserName
	user_loginID := pm.LoginID
	if "sivan" != user_name {
		panic("无法登录")
	}
	loginID, err := db.RedisGet("login-" + user_name)
	if nil != err {
		panic(fmt.Sprintf("%s", err))
	}
	if "" == loginID || loginID != user_loginID {
		panic("请先登录")
	}
	o := orm.NewOrm()
	var maps []orm.Params
	count := 0
	if "ALL" == pm.PwdId {
		sql := "select count(1) as count from pwd_map"
		beego.Info(sql)
		o.Raw(sql).Values(&maps)
		count_f, _ := strconv.ParseInt(maps[0]["count"].(string), 10, 64)
		count = int(count_f)
		sql = fmt.Sprintf("select * from pwd_map limit %d, %d", pm.From, pm.Page)
		beego.Info(sql)
		o.Raw(sql).Values(&maps)
	} else {
		sql := fmt.Sprintf("select * from pwd_map where id = '%s'", pm.PwdId)
		beego.Info(sql)
		o.Raw(sql).Values(&maps)
		count = len(maps)
	}
	if 0 == len(maps) {
		panic("没有数据")
	}
	c.Data["json"] = map[string]interface{}{
		"pwd":   maps,
		"count": count,
		"error": "",
	}
	c.ServeJSON()
}
